package com.wxq.member.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wxq.common.exception.BizCode;
import com.wxq.common.utils.HttpUtils;
import com.wxq.common.utils.JsonUtils;
import com.wxq.member.dao.MemberLevelDao;
import com.wxq.member.entity.MemberLevelEntity;
import com.wxq.member.exception.MemberException;
import com.wxq.member.vo.MemberLoginVO;
import com.wxq.member.vo.MemberRegisterVO;
import com.wxq.member.vo.WeiboUser;
import com.wxq.member.dao.MemberDao;
import com.wxq.member.entity.MemberEntity;
import com.wxq.member.service.MemberService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxq.common.utils.PageUtils;
import com.wxq.common.utils.Query;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户名唯一性校验
     * @param username
     */
    @Override
    public void checkUsernameUnique(String username) throws MemberException {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username",username));
        if (count > 0){
            throw new MemberException(BizCode.USER_EXIST_EXCEPTION.getMessage(),BizCode.USER_EXIST_EXCEPTION.getCode());
        }

    }

    /**
     * 电话唯一性校验
     * @param mobile
     */
    @Override
    public void checkMobileUnique(String mobile) {
        Long count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile",mobile));
        if (count > 0){
            throw new MemberException(BizCode.USER_EXIST_EXCEPTION.getMessage(),BizCode.MOBILE_EXIST_EXCEPTION.getCode());
        }
    }

    @Override
    public void register(MemberRegisterVO registerVO) throws  MemberException{
        //检车用户名和手机号是否唯一
        checkUsernameUnique(registerVO.getUsername());
        checkMobileUnique(registerVO.getMobile());
        //设置用户名手机号
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(registerVO.getUsername());;
        memberEntity.setMobile(registerVO.getMobile());
        //设置网名,默认是用户名
        memberEntity.setNickname(registerVO.getUsername());
        //设置会员默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //设置密码
        //加密，🧵生成盐值，根据盐值以及明文密码生成密文
        //密码匹配
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePassword = passwordEncoder.encode(registerVO.getPassword());
        memberEntity.setPassword(encodePassword);
        //保存
        save(memberEntity);
    }

    /**
     * 登陆
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVO vo) {
        String account = vo.getAccount();;
        String password = vo.getPassword();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username",account)
        .or().eq("mobile",account));
        if (entity != null){
            //密文
            String passwordDb = entity.getPassword();
            //密码匹配
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matchs = passwordEncoder.matches(password,passwordDb);
            if (matchs){
                return entity;
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 微博登陆
     * @param weiboUser
     * @return
     */
    @Override
    public MemberEntity login(WeiboUser weiboUser) {
        //登陆和注册洛基合并
        //判断当前用户是否登陆过
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("weibo_uid",weiboUser.getUid()));
        if (memberEntity != null){
            //用户已经注册，更新access_token和expires_in
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(memberEntity.getId());
            updateEntity.setAccessToken(weiboUser.getAccess_token());
            updateEntity.setExpiresIn(weiboUser.getExpires_in());
            baseMapper.updateById(updateEntity);
            memberEntity.setAccessToken(weiboUser.getAccess_token());
            memberEntity.setExpiresIn(weiboUser.getExpires_in());
            return memberEntity;
        } else {
            //没有查询到微博用户，则需要注册
            MemberEntity regEntity = new MemberEntity();
            //查询当前微博用户到社交账号信息
            Map<String, String> querys = new HashMap<>(2);
            querys.put("access_token",weiboUser.getAccess_token());
            querys.put("uid",weiboUser.getUid());
            try {
                HttpResponse response = HttpUtils.doGet("https://api/weibo.com",
                        "/2/users/show.json","get",new HashMap<String, String>(0),querys);
                if (response.getStatusLine().getStatusCode() == 200){
                    String json = EntityUtils.toString(response.getEntity());
                    Map<String, String> map = JsonUtils.jsonToObject(json, new TypeReference<Map<String, String>>() {});
                    //昵称
                    String name = map.get("name");
                    //性质
                    String gender = map.get("gender");
                    regEntity.setNickname(name);
                    regEntity.setGender("m".equals(gender)?1:0);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            regEntity.setWeiboUid(weiboUser.getUid());
            regEntity.setAccessToken(weiboUser.getAccess_token());
            regEntity.setExpiresIn(weiboUser.getExpires_in());
            baseMapper.insert(regEntity);
            return regEntity;
        }
    }

}